home *** CD-ROM | disk | FTP | other *** search
/ Atari Mega Archive 1 / Atari Mega Archive - Volume 1.iso / gnu / bash / bash_110 / mint / glob.zoo / glob / glob.c < prev    next >
Encoding:
C/C++ Source or Header  |  1991-07-28  |  14.3 KB  |  639 lines

  1. /* File-name wildcard pattern matching for GNU.
  2.    Copyright (C) 1985, 1988, 1989 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 1, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18. /* To whomever it may concern: I have never seen the code which most
  19.    Unix programs use to perform this function.  I wrote this from scratch
  20.    based on specifications for the pattern matching.  --RMS.  */
  21.  
  22. #if defined (SHELL)
  23. #  include <config.h>
  24. #endif
  25.  
  26. #if defined (USG) && !defined (Xenix)
  27. #  if !defined (USGr3)
  28. #    define USGr3
  29. #endif /* USGr3 */
  30. #endif /* USG && !Xenix */
  31.  
  32. #include <sys/types.h>
  33.  
  34. #if defined (USGr3) || defined (DIRENT)
  35. #  include <dirent.h>
  36. #  define direct dirent
  37. #  define    D_NAMLEN(d) strlen((d)->d_name)
  38. #else
  39. #  define D_NAMLEN(d) ((d)->d_namlen)
  40. #  if defined (Xenix)
  41. #    include <sys/ndir.h>
  42. #  else
  43. #    if defined (USG)
  44. #      include "ndir.h"
  45. #     else
  46. #      include <sys/dir.h>
  47. #    endif
  48. #  endif
  49. #endif    /* USGr3 || DIRENT.  */
  50.  
  51. #if defined (_POSIX_SOURCE)
  52. /* Posix does not require that the d_ino field be present, and some
  53.    systems do not provide it. */
  54. #define REAL_DIR_ENTRY(dp) 1
  55. #else
  56. #define REAL_DIR_ENTRY(dp) (dp->d_ino != 0)
  57. #endif /* _POSIX_SOURCE */
  58.  
  59.  
  60. #if defined (NeXT)
  61. #include <string.h>
  62. #else
  63. #if defined (USG)
  64. #if !defined (isc386)
  65. #  include <memory.h>
  66. #endif
  67. #include <string.h>
  68. #if defined (RISC6000)
  69. extern void bcopy ();
  70. #else /* RISC6000 */
  71. #define bcopy(s, d, n) ((void) memcpy ((d), (s), (n)))
  72. #endif /* RISC6000 */
  73. #define rindex    strrchr
  74.  
  75. #else /* !USG */
  76. #include <strings.h>
  77.  
  78. extern void bcopy ();
  79. #endif /* !USG */
  80. #endif /* !NeXT */
  81.  
  82. /* If the opendir () on your system lets you open non-directory files,
  83.    then we consider that not robust.  Define OPENDIR_NOT_ROBUST in the
  84.    SYSDEP_CFLAGS for your machines entry in machines.h. */
  85. #if defined (OPENDIR_NOT_ROBUST)
  86. #if defined (SHELL)
  87. # include "posixstat.h"
  88. #else
  89. # include <sys/stat.h>
  90. #endif /* SHELL */
  91. #endif /* OPENDIR_NOT_ROBUST */
  92.  
  93. extern char *malloc (), *realloc ();
  94. extern void free ();
  95.  
  96. #ifndef NULL
  97. #define NULL 0
  98. #endif
  99.  
  100. /* Global variable which controls whether or not * matches .*.
  101.    Non-zero means don't match .*.  */
  102. int noglob_dot_filenames = 1;
  103.  
  104.  
  105. static int glob_match_after_star ();
  106.  
  107. /* Return nonzero if PATTERN has any special globbing chars in it.  */
  108. int
  109. glob_pattern_p (pattern)
  110.      char *pattern;
  111. {
  112.   register char *p = pattern;
  113.   register char c;
  114.   int    open = 0;
  115.  
  116.   while ((c = *p++) != '\0')
  117.     switch (c)
  118.       {
  119.       case '?':
  120.       case '*':
  121.     return 1;
  122.  
  123.       case '[':        /* Only accept an open brace if there is a close */
  124.     open++;        /* brace to match it.  Bracket expressions must be */
  125.     continue;    /* complete, according to Posix.2 */
  126.       case ']':
  127.     if (open)
  128.       return 1;
  129.     continue;      
  130.  
  131.       case '\\':
  132.     if (*p++ == '\0')
  133.       return 0;
  134.       }
  135.  
  136.   return 0;
  137. }
  138.  
  139. /* Match the pattern PATTERN against the string TEXT;
  140.    return 1 if it matches, 0 otherwise.
  141.  
  142.    A match means the entire string TEXT is used up in matching.
  143.  
  144.    In the pattern string, `*' matches any sequence of characters,
  145.    `?' matches any character, [SET] matches any character in the specified set,
  146.    [!SET] matches any character not in the specified set.
  147.  
  148.    A set is composed of characters or ranges; a range looks like
  149.    character hyphen character (as in 0-9 or A-Z).
  150.    [0-9a-zA-Z_] is the set of characters allowed in C identifiers.
  151.    Any other character in the pattern must be matched exactly.
  152.  
  153.    To suppress the special syntactic significance of any of `[]*?!-\',
  154.    and match the character exactly, precede it with a `\'.
  155.  
  156.    If DOT_SPECIAL is nonzero,
  157.    `*' and `?' do not match `.' at the beginning of TEXT.  */
  158. int
  159. glob_match (pattern, text, dot_special)
  160.      char *pattern, *text;
  161.      int dot_special;
  162. {
  163.   register char *p = pattern, *t = text;
  164.   register char c;
  165.  
  166.   while ((c = *p++) != '\0')
  167.     switch (c)
  168.       {
  169.       case '?':
  170.     if (*t == '\0' || (dot_special && t == text && *t == '.'))
  171.       return 0;
  172.     else
  173.       ++t;
  174.     break;
  175.  
  176.       case '\\':
  177.     if (*p++ != *t++)
  178.       return 0;
  179.     break;
  180.  
  181.       case '*':
  182.     if (dot_special && t == text && *t == '.')
  183.       return 0;
  184.     return glob_match_after_star (p, t);
  185.  
  186.       case '[':
  187.     {
  188.       register char c1 = *t++;
  189.       int invert;
  190.  
  191.       if (!c1)
  192.         return (0);
  193.  
  194.       invert = ((*p == '!') || (*p == '^'));
  195.       if (invert)
  196.         p++;
  197.  
  198.       c = *p++;
  199.       while (1)
  200.         {
  201.           register char cstart = c, cend = c;
  202.  
  203.           if (c == '\\')
  204.         {
  205.           cstart = *p++;
  206.           cend = cstart;
  207.         }
  208.  
  209.           if (c == '\0')
  210.         return 0;
  211.  
  212.           c = *p++;
  213.           if (c == '-' && *p != ']')
  214.         {
  215.           cend = *p++;
  216.           if (cend == '\\')
  217.             cend = *p++;
  218.           if (cend == '\0')
  219.             return 0;
  220.           c = *p++;
  221.         }
  222.           if (c1 >= cstart && c1 <= cend)
  223.         goto match;
  224.           if (c == ']')
  225.         break;
  226.         }
  227.       if (!invert)
  228.         return 0;
  229.       break;
  230.  
  231.     match:
  232.       /* Skip the rest of the [...] construct that already matched.  */
  233.       while (c != ']')
  234.         { 
  235.           if (c == '\0')
  236.         return 0;
  237.           c = *p++;
  238.           if (c == '\0')
  239.         return 0;
  240.           else if (c == '\\')
  241.         ++p;
  242.         }
  243.       if (invert)
  244.         return 0;
  245.       break;
  246.     }
  247.  
  248.       default:
  249.     if (c != *t++)
  250.       return 0;
  251.       }
  252.  
  253.   return *t == '\0';
  254. }
  255.  
  256. /* Like glob_match, but match PATTERN against any final segment of TEXT.  */
  257.  
  258. static int
  259. glob_match_after_star (pattern, text)
  260.      char *pattern, *text;
  261. {
  262.   register char *p = pattern, *t = text;
  263.   register char c, c1;
  264.  
  265.   while ((c = *p++) == '?' || c == '*')
  266.     if (c == '?' && *t++ == '\0')
  267.       return 0;
  268.  
  269.   if (c == '\0')
  270.     return 1;
  271.  
  272.   if (c == '\\')
  273.     c1 = *p;
  274.   else
  275.     c1 = c;
  276.  
  277.   while (1)
  278.     {
  279.       if ((c == '[' || *t == c1) && glob_match (p - 1, t, 0))
  280.     return 1;
  281.       if (*t++ == '\0')
  282.     return 0;
  283.     }
  284. }
  285.  
  286. /* Return a vector of names of files in directory DIR
  287.    whose names match glob pattern PAT.
  288.    The names are not in any particular order.
  289.    Wildcards at the beginning of PAT do not match an initial period.
  290.  
  291.    The vector is terminated by an element that is a null pointer.
  292.  
  293.    To free the space allocated, first free the vector's elements,
  294.    then free the vector.
  295.  
  296.    Return 0 if cannot get enough memory to hold the pointer
  297.    and the names.
  298.  
  299.    Return -1 if cannot access directory DIR.
  300.    Look in errno for more information.  */
  301.  
  302. char **
  303. glob_vector (pat, dir)
  304.      char *pat;
  305.      char *dir;
  306. {
  307.   struct globval
  308.     {
  309.       struct globval *next;
  310.       char *name;
  311.     };
  312.  
  313.   DIR *d;
  314.   register struct direct *dp;
  315.   struct globval *lastlink;
  316.   register struct globval *nextlink;
  317.   register char *nextname;
  318.   unsigned int count;
  319.   int lose;
  320.   register char **name_vector;
  321.   register unsigned int i;
  322. #if defined (OPENDIR_NOT_ROBUST)
  323.   struct stat finfo;
  324.  
  325.   if (stat (dir, &finfo) < 0)
  326.     return ((char **)-1);
  327.  
  328.   if (!S_ISDIR (finfo.st_mode))
  329.     return ((char **)-1);
  330. #endif /* OPENDIR_NOT_ROBUST */
  331.  
  332.   d = opendir (dir);
  333.   if (d == NULL)
  334.     return (char **) -1;
  335.  
  336.   lastlink = 0;
  337.   count = 0;
  338.   lose = 0;
  339.  
  340.   /* Scan the directory, finding all names that match.
  341.      For each name that matches, allocate a struct globval
  342.      on the stack and store the name in it.
  343.      Chain those structs together; lastlink is the front of the chain.  */
  344.   while (1)
  345.     {
  346. #if defined (SHELL)
  347.       /* Make globbing interruptible in the bash shell. */
  348.       extern int interrupt_state;
  349.  
  350.       if (interrupt_state)
  351.     {
  352.       closedir (d);
  353.       lose = 1;
  354.       goto lost;
  355.     }
  356. #endif /* SHELL */
  357.       
  358.       dp = readdir (d);
  359.       if (dp == NULL)
  360.     break;
  361.  
  362.       /* If this directory entry is not to be used, try again. */
  363.       if (!REAL_DIR_ENTRY (dp))
  364.     continue;
  365.  
  366.       /* If a dot must be explicity matched, check to see if they do. */
  367.       if (noglob_dot_filenames && dp->d_name[0] == '.' && pat[0] != '.')
  368.     continue;
  369.  
  370.       if (glob_match (pat, dp->d_name, noglob_dot_filenames))
  371.     {
  372.       nextlink = (struct globval *) alloca (sizeof (struct globval));
  373.       nextlink->next = lastlink;
  374.       nextname = (char *) malloc (D_NAMLEN(dp) + 1);
  375.       if (nextname == NULL)
  376.         {
  377.           lose = 1;
  378.           break;
  379.         }
  380.       lastlink = nextlink;
  381.       nextlink->name = nextname;
  382.       bcopy (dp->d_name, nextname, D_NAMLEN(dp) + 1);
  383.       ++count;
  384.     }
  385.     }
  386.   (void) closedir (d);
  387.  
  388.   if (!lose)
  389.     {
  390.       name_vector = (char **) malloc ((count + 1) * sizeof (char *));
  391.       lose |= name_vector == NULL;
  392.     }
  393.  
  394.   /* Have we run out of memory?     */
  395.  lost:
  396.   if (lose)
  397.     {
  398.       /* Here free the strings we have got.  */
  399.       while (lastlink)
  400.     {
  401.       free (lastlink->name);
  402.       lastlink = lastlink->next;
  403.     }
  404.       return NULL;
  405.     }
  406.  
  407.   /* Copy the name pointers from the linked list into the vector.  */
  408.   for (i = 0; i < count; ++i)
  409.     {
  410.       name_vector[i] = lastlink->name;
  411.       lastlink = lastlink->next;
  412.     }
  413.  
  414.   name_vector[count] = NULL;
  415.   return name_vector;
  416. }
  417.  
  418. /* Return a new array which is the concatenation
  419.    of each string in ARRAY to DIR. */
  420.  
  421. static char **
  422. glob_dir_to_array (dir, array)
  423.      char *dir, **array;
  424. {
  425.   register unsigned int i, l;
  426.   int add_slash;
  427.   char **result;
  428.  
  429.   l = strlen (dir);
  430.   if (l == 0)
  431.     return array;
  432.  
  433.   add_slash = dir[l - 1] != '/';
  434.  
  435.   i = 0;
  436.   while (array[i] != NULL)
  437.     ++i;
  438.  
  439.   result = (char **) malloc ((i + 1) * sizeof (char *));
  440.   if (result == NULL)
  441.     return NULL;
  442.  
  443.   for (i = 0; array[i] != NULL; i++)
  444.     {
  445.       result[i] = (char *) malloc (l + (add_slash ? 1 : 0)
  446.                    + strlen (array[i]) + 1);
  447.       if (result[i] == NULL)
  448.     return NULL;
  449.       sprintf (result[i], "%s%s%s", dir, add_slash ? "/" : "", array[i]);
  450.     }
  451.   result[i] = NULL;
  452.  
  453.   /* Free the input array.  */
  454.   for (i = 0; array[i] != NULL; i++)
  455.     free (array[i]);
  456.   free ((char *) array);
  457.  
  458.   return result;
  459. }
  460.  
  461. /* Do globbing on PATHNAME.  Return an array of pathnames that match,
  462.    marking the end of the array with a null-pointer as an element.
  463.    If no pathnames match, then the array is empty (first element is null).
  464.    If there isn't enough memory, then return NULL.
  465.    If a file system error occurs, return -1; `errno' has the error code.  */
  466. char **
  467. glob_filename (pathname)
  468.      char *pathname;
  469. {
  470.   char **result;
  471.   unsigned int result_size;
  472.   char *directory_name, *filename;
  473.   unsigned int directory_len;
  474.  
  475.   result = (char **) malloc (sizeof (char *));
  476.   result_size = 1;
  477.   if (result == NULL)
  478.     return NULL;
  479.  
  480.   result[0] = NULL;
  481.  
  482.   /* Find the filename.  */
  483.   filename = rindex (pathname, '/');
  484.   if (filename == NULL)
  485.     {
  486.       filename = pathname;
  487.       directory_name = "";
  488.       directory_len = 0;
  489.     }
  490.   else
  491.     {
  492.       directory_len = (filename - pathname) + 1;
  493.       directory_name = (char *) alloca (directory_len + 1);
  494.  
  495.       bcopy (pathname, directory_name, directory_len);
  496.       directory_name[directory_len] = '\0';
  497.       ++filename;
  498.     }
  499.  
  500.   /* If directory_name contains globbing characters, then we
  501.      have to expand the previous levels.  Just recurse. */
  502.   if (glob_pattern_p (directory_name))
  503.     {
  504.       char **directories;
  505.       register unsigned int i;
  506.  
  507.       if (directory_name[directory_len - 1] == '/')
  508.     directory_name[directory_len - 1] = '\0';
  509.  
  510.       directories = glob_filename (directory_name);
  511.  
  512.       if (directories == NULL)
  513.     goto memory_error;
  514.       else if ((int) directories == -1)
  515.     return (char **) -1;
  516.       else if (*directories == NULL)
  517.     {
  518.       free ((char *) directories);
  519.       return (char **) -1;
  520.     }
  521.  
  522.       /* We have successfully globbed the preceding directory name.
  523.      For each name in DIRECTORIES, call glob_vector on it and
  524.      FILENAME.  Concatenate the results together.  */
  525.       for (i = 0; directories[i] != NULL; ++i)
  526.     {
  527.       char **temp_results = glob_vector (filename, directories[i]);
  528.  
  529.       /* Handle error cases. */
  530.       if (temp_results == NULL)
  531.         goto memory_error;
  532.       else if (temp_results == (char **)-1)
  533.         /* This filename is probably not a directory.  Ignore it.  */
  534.         ;
  535.       else
  536.         {
  537.           char **array = glob_dir_to_array (directories[i], temp_results);
  538.           register unsigned int l;
  539.  
  540.           l = 0;
  541.           while (array[l] != NULL)
  542.         ++l;
  543.  
  544.           result =
  545.         (char **)realloc (result, (result_size + l) * sizeof (char *));
  546.  
  547.           if (result == NULL)
  548.         goto memory_error;
  549.  
  550.           for (l = 0; array[l] != NULL; ++l)
  551.         result[result_size++ - 1] = array[l];
  552.  
  553.           result[result_size - 1] = NULL;
  554.  
  555.           /* Note that the elements of ARRAY are not freed.  */
  556.           free ((char *) array);
  557.         }
  558.     }
  559.       /* Free the directories.  */
  560.       for (i = 0; directories[i]; i++)
  561.     free (directories[i]);
  562.  
  563.       free ((char *) directories);
  564.  
  565.       return result;
  566.     }
  567.  
  568.   /* If there is only a directory name, return it. */
  569.   if (*filename == '\0')
  570.     {
  571.       result = (char **) realloc ((char *) result, 2 * sizeof (char *));
  572.       if (result == NULL)
  573.     return NULL;
  574.       result[0] = (char *) malloc (directory_len + 1);
  575.       if (result[0] == NULL)
  576.     goto memory_error;
  577.       bcopy (directory_name, result[0], directory_len + 1);
  578.       result[1] = NULL;
  579.       return result;
  580.     }
  581.   else
  582.     {
  583.       /* Otherwise, just return what glob_vector
  584.      returns appended to the directory name. */
  585.       char **temp_results = glob_vector (filename,
  586.                      (directory_len == 0
  587.                       ? "." : directory_name));
  588.  
  589.       if (temp_results == NULL || temp_results == (char **)-1)
  590.     return temp_results;
  591.  
  592.       return (glob_dir_to_array (directory_name, temp_results));
  593.     }
  594.  
  595.   /* We get to memory error if the program has run out of memory, or
  596.      if this is the shell, and we have been interrupted. */
  597.  memory_error:
  598.   if (result != NULL)
  599.     {
  600.       register unsigned int i;
  601.       for (i = 0; result[i] != NULL; ++i)
  602.     free (result[i]);
  603.       free ((char *) result);
  604.     }
  605. #if defined (SHELL)
  606.   {
  607.     extern int interrupt_state;
  608.  
  609.     if (interrupt_state)
  610.       throw_to_top_level ();
  611.   }
  612. #endif /* SHELL */
  613.   return NULL;
  614. }
  615.  
  616. #ifdef TEST
  617.  
  618. main (argc, argv)
  619.      int argc;
  620.      char **argv;
  621. {
  622.   unsigned int i;
  623.  
  624.   for (i = 1; i < argc; ++i)
  625.     {
  626.       char **value = glob_filename (argv[i]);
  627.       if (value == NULL)
  628.     puts ("Out of memory.");
  629.       else if ((int) value == -1)
  630.     perror (argv[i]);
  631.       else
  632.     for (i = 0; value[i] != NULL; i++)
  633.       puts (value[i]);
  634.     }
  635.  
  636.   exit (0);
  637. }
  638. #endif    /* TEST.  */
  639.